package com.starfleet.lcars

import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.starfleet.lcars.ui.theme.LCARSTricorderTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.tricorder_webview)//Here you can see,A webview program must initiate webview before "findViewById".Otherwise,the program is gonna crash.
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT)  //Well..It's after all a Tricorder.It doesn't seem right to put it horizontally.Therefore, we removed the ability to rotate the device and re-adjust the Android webview page to horizontal.
        val ConnectWebView:WebView = findViewById(R.id.webview)
        ConnectWebView.addJavascriptInterface(WebAppInterface(this), "AndroidSysToast") /* see class 'WebAppInterface' below. */
        TricorderInterface(ConnectWebView)

    }
}

/** Instantiate the interface and set the context.  */
class WebAppInterface(private val mContext: Context) {

    /** Show a toast from the web page.  */
    @JavascriptInterface
    fun showToast(toast: String) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
    }
}

fun TricorderInterface (ConnectWebView:WebView) {
    // Allow JavaScript to run.
    ConnectWebView.settings.javaScriptEnabled = true //In this program, the setting made it possible to fetch "time and date", also scroll up via jQuery, whose scripts are defined in lcars.js.


    // 确保跳转到另一个网页时仍然在当前 WebView 中显示
    // 而不是调用浏览器打开
    //Made it possible to run multiple websites in a single app.
    ConnectWebView.webViewClient = WebViewClient()


    // 设置 WebView 的按键监听器，覆写监听器的 onKey 函数，对返回键作特殊处理
    // 当 WebView 可以返回到上一个页面时回到上一个页面
    //That one was copied without any idea for me,don't mind.
    ConnectWebView.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
        if (keyCode == KeyEvent.KEYCODE_BACK && ConnectWebView.canGoBack()) {
            ConnectWebView.goBack()
            return@OnKeyListener true
        }
        false
    })



    ConnectWebView.loadUrl("file:///android_asset/lcars-standard-picard-tricordermain.html")
}


@Preview(showBackground = true, showSystemUi = true)
@Composable
fun GreetingPreview() {
    LCARSTricorderTheme {
    //unable to call 'this' context from here, Preview is deprecated.
    }
}